package com.jboltai.util.text;

import cn.hutool.core.util.StrUtil;
import com.jboltai.event.text.TextEvent;
import org.apache.tika.metadata.Metadata;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.function.Consumer;

public class DocxContentHandler extends BaseContentHandler {
    public DocxContentHandler(Consumer<String> consumer, TextEvent event, Map<String, FileInfo> fileInfoMap) {
        super(consumer, event, fileInfoMap);
    }

    @Override
    public void startElement(String uri, String localName, String name, Attributes attrs) throws SAXException {
        super.startElement(uri, localName, name, attrs);

        if (!StrUtil.equalsAny(localName, TAG_IMG, TAG_DIV)) {
            return;
        }

        FileInfo fileInfo = null;
        if (TAG_DIV.equals(localName)) {
            fileInfo = getFile(attrs);
        }
//        if (TAG_DIV.equals(localName)) {
//            fileInfo = getFile(attrs);
//        } else if (TAG_IMG.equals(localName)) {
//            fileInfo = getImage(attrs);
//        }

        if (fileInfo == null) {
            return;
        }

        String convertText = "";
        if (file2TextConverter != null) {
            convertText = file2TextConverter.convert(event, fileInfo);
//            fileInfo.setConvertText(convertText);
        }
        consumer.accept(convertText);
    }

    private FileInfo getImage(Attributes attrs) {
        String resourceName = attrs.getValue("src");
        if (StrUtil.isBlank(resourceName)) {
            return null;
        }
        resourceName = resourceName.replace("embedded:", "");
        if (resourceName.contains("emf")) {
            return null;
        }
        return fileInfoMap.get(resourceName);
    }

    private FileInfo getFile(Attributes attrs) {
        String resourceName = attrs.getValue("id");
        String data = attrs.getValue("data");
        if (StrUtil.isBlank(resourceName) || StrUtil.isBlank(data)) {
            return null;
        }
        if(!data.equals("custom")){
            return null;
        }
        return fileInfoMap.get(resourceName);
    }

    @Override
    public void parseEmbedded(InputStream is, ContentHandler contentHandler, Metadata metadata, boolean b) throws SAXException, IOException {
        String resourceName = metadata.get("resourceName");

        if (StrUtil.isBlank(resourceName)) {
            return;
        }

        FileInfo fileInfo = fileInfoMap.get(resourceName);
        if (fileInfo == null) {
            return;
        }
        if (fileStreamExtractor != null) {
            fileStreamExtractor.extract(event, is, fileInfo);
        }
    }
}
